package project.web.menu;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import online.filter.FilterUtil;
import online.filter.SessionAttributeFilter;
import online.model.annotation.NoTransaction;
import online.struts.mapping.RequestMapping;

import org.apache.logging.log4j.LogManager;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ActionConfig;

/**
 * 準備アクション
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
@NoTransaction
public final class PreparingAction extends Action {

	/**
	 * @see online.struts.action.BaseAction
	 * #execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(final ActionMapping mapping,
			final ActionForm form, final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {

		String val = request.getParameter("path");
		if (!Objects.toString(val, "").trim().isEmpty()) {
			ActionConfig ac = mapping.getModuleConfig().findActionConfig("/" + val);
			if (RequestMapping.class.isInstance(ac)) {
				RequestMapping rm = RequestMapping.class.cast(ac);
				// セション情報削除
				if (rm.getKeepId() != null && !rm.isMultipleKeep()) {
					SessionAttributeFilter.unbound(request, rm.getKeepId());
				}

				try {
					response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
					response.setHeader("Location",
							response.encodeRedirectURL(getLocation(val, request)));
					response.setContentLength(0);
					response.flushBuffer();
				} catch (IOException ex) {
					LogManager.getLogger().info(ex.getMessage());
				}
				return null;
			}
		}

		try {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			response.flushBuffer();
		} catch (IOException ex) {
			LogManager.getLogger().info(ex.getMessage());
		}
		return null;
	}

	/**
	 * Location取得
	 *
	 * @param str パス
	 * @param request リクエスト
	 * @return Location
	 */
	private String getLocation(final String str, final HttpServletRequest request) {
		String uri = request.getRequestURI();
		String qry = FilterUtil.stripParameter(request.getQueryString(), "path");
		String ret = uri.substring(0, uri.lastIndexOf('/') + "/".length()) + str + ".do";
		if (!qry.isEmpty()) {
			return ret + "?" + qry;
		}
		return ret;
	}
}
